<?php

namespace WenRuns\Laravel\Admin\Form\Field\Grid\Field;

use WenRuns\Laravel\Admin\Form\Field\Grid\Column;
use WenRuns\Laravel\Admin\Form\Field\Grid\Grid;

class Tab extends Column
{
    /**
     * @var string
     */
    protected $type = 'tab';

    /**
     * @var array
     */
    protected $items = [];


    /**
     * @param Grid $grid
     * @param $closure
     * @param $label
     */
    public function __construct(Grid $grid, $closure, $label = '')
    {
        parent::__construct($grid, null, $label);
        call_user_func($closure, $this);
    }


    /**
     * @param $title
     * @param \Closure $closure
     * @param $column
     * @return TabRow
     */
    public function add($title, \Closure $closure, $column = null)
    {
        $item = new TabRow($this->grid, $title, $closure, $this, $column);
        $item->config('columnWidth', $this->configs['columnWidth'] ?? 6);
        $this->items[] = $item;
        return $item;
    }

    /**
     * @return array
     */
    public function render()
    {
        $res = parent::render();
        $res['items'] = $this->renderItems();
        return $res;
    }


    /**
     * @return array
     */
    protected function renderItems()
    {
        $items = [];
        foreach ($this->items as $vo) {
            /** @var TabRow $vo */
            $items[] = $vo->render();
        }
        return $items;
    }

    /**
     * 设置位置， top, left, bottom, right
     * @param $pos
     * @return $this
     */
    public function position($pos = 'top')
    {
        return $this->config('position', $pos);
    }

    public function columnWidth($width = 6)
    {
        foreach ($this->items as $item) {
            /** @var TabRow $item */
            if ($item->priority()) {
                continue;
            }
            $item->config('columnWidth', $width);
        }
        return $this->config('columnWidth', $width);
    }
}
